package crazyjava;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final ReadWriteClass readWriteClass = new ReadWriteClass();
		for(int i=0;i<3;i++){
			new Thread(new Runnable() {
				
				public void run() {
					
					readWriteClass.get();
				}
			}).start();
			new Thread(new Runnable() {
				
				public void run() {
					
					readWriteClass.put();
				}
			}).start();
		}

	}

}
class ReadWriteClass{
	
	private ReadWriteLock rwl = new ReentrantReadWriteLock();
	
	public void get(){
	
		rwl.readLock().lock();
		try {
			System.out.println(Thread.currentThread().getName()+" is ready to read!!");
			Thread.sleep(100);
			System.out.println(Thread.currentThread().getName()+" has readed");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			rwl.readLock().unlock();
		}
		
	}
	
	public void put(){
		
		rwl.writeLock().lock();
		try {
			System.out.println(Thread.currentThread().getName()+" is ready to write!!");
			Thread.sleep(100);
			System.out.println(Thread.currentThread().getName()+" has writen!!");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			rwl.writeLock().unlock();
		}
		
		
	}
}